package com.tyun.modules.sys.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tyun.common.aspect.BaseLog;
import com.tyun.common.utils.BaseConstant;
import com.tyun.common.utils.R;
import com.tyun.modules.sys.entity.SysMenu;
import com.tyun.modules.sys.service.ISysMenuService;
import com.tyun.modules.sys.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author taocongcong
 * @create 2017-12-15 13:50
 */
@RestController
@RequestMapping("sysMenu")
public class SysMenuController extends CommonController{

    private static final Logger logger = LogManager.getLogger(SysMenuController.class);

    @Autowired
    private ISysMenuService sysMenuService;
    @Autowired
    private ISysUserService sysUserService;

    @BaseLog("查询所有菜单")
    @GetMapping("/list")
    public R list(SysMenu sysMenu){
        EntityWrapper<SysMenu> ew = new EntityWrapper<>(sysMenu);
        List<SysMenu> sysMenuList = sysMenuService.selectList(ew);
        logger.info("在" + new Date() + "查询所有菜单");
        return R.ok().put("menuList", sysMenuList);
    }

    @BaseLog("查询所有菜单")
    @GetMapping("/list/{roleId}")
    public R roleMenuTreeData(@PathVariable String roleId, SysMenu sysMenu){
        List<Map<String, Object>> tree = sysMenuService.roleMenuTreeData(sysMenu, roleId);
        return R.ok().put("tree", tree);
    }

    @GetMapping("/listChildren")
    public JSONArray listChildren(SysMenu sysMenu){
        sysMenu.setRemovetag("N");
        EntityWrapper<SysMenu> ew = new EntityWrapper<>(sysMenu);
        List<SysMenu> sysMenuList = sysMenuService.selectList(ew);
        JSONArray rows = new JSONArray();
        if (sysMenuList != null && sysMenuList.size() > 0) {
            JSONObject row = null;
            for (SysMenu item : sysMenuList) {
                row = new JSONObject();
                row.put("name", item.getName());
                row.put("url", item.getUrl());
                row.put("Id", item.getMenuId());
                row.put("type", item.getType());
                row.put("perms", item.getPerms());
                if (!StringUtils.equals(item.getParentId(),"0")) {
                    row.put("ParentId", item.getParentId());
                }
                rows.add(row);
            }
        }
        return rows;
    }
    
    @GetMapping("queryUserMenuList")
    public R queryUserMenuList(){
        // 根据角色查询
        List<SysMenu> sysMenuList = sysMenuService.queryUserMenuList(getUserId());
        Set<String> permissions = sysUserService.queryUserMenuPermsList(getUserId());
        return R.ok().put("menuList", sysMenuList).put("permissions", permissions);
    }

    @GetMapping("/page")
    public Page<SysMenu> page(Page<SysMenu> page, SysMenu sysMenu){
        sysMenuService.selectPage(page, new EntityWrapper<>(sysMenu));
        return page;
    }

    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    @RequiresPermissions("sys:menu:info")
    public R info(@PathVariable String menuId){
        SysMenu menu = sysMenuService.selectById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @BaseLog("保存菜单")
    @RequestMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public R save(@RequestBody SysMenu menu){
        menu.setMenuId(UUID.randomUUID().toString());
        menu.setRemovetag(BaseConstant.REMOVE_N);
        boolean flag = sysMenuService.insert(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @BaseLog("修改菜单")
    @RequestMapping("/update")
    @RequiresPermissions("sys:menu:update")
    public R update(@RequestBody SysMenu menu){
        boolean flag = sysMenuService.updateById(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{menuId}")
    @RequiresPermissions("sys:menu:delete")
    public R delete(@PathVariable String menuId){
        // 查询是否存在子菜单
        // List<SysMenu> sysMenuList = sysMenuService.queryListParentId(menuId, null);
        SysMenu record = new SysMenu();
        record.setParentId(menuId);
        EntityWrapper<SysMenu> ew = new EntityWrapper<>(record);
        int count = sysMenuService.selectCount(ew);
        if (count > 0) {
            return R.error("存在子菜单，不允许删除");
        }
        SysMenu menu = sysMenuService.selectById(menuId);
        menu.setRemovetag(BaseConstant.REMOVE_Y);
        // boolean flag = sysMenuService.deleteById(menuId);
        boolean flag = sysMenuService.updateById(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}
